// index.ts
// 获取应用实例
import { RCSP, RCSPManager } from "../../lib/rcsp-impl/rcsp"
import { DeviceManager, DeviceBluetooth } from "../../lib/rcsp-impl/dev-bluetooth";
import { BluetoothDevice } from "../../lib/rcsp-protocol/rcsp-util";
import { wxBluetooth } from "../../lib/rcsp-impl/bluetooth";
import api from "../../api/index";
const i18n = require('../../i18n/index');

Page({
  data: {
    isScaning: false,
    scanDevices: new Array(),
    triggered: false,
    filterDevName: 'JL707',
    connectedDeviceId: "",
    fromDevice: false, // 标记是否从设备页面跳转过来
    isBinding: false,  // 标记是否正在绑定设备
    bindingProgress: '', // 绑定进度文本
    // 多语言
    l10n: {}
  },
  _freshing: false,
  _lastUpdateTime: 0,
  _foundSrcDevlist: new Array(),
  _RCSPWrapperEventCallback: RCSP.RCSPWrapperEventCallback.prototype,
  onLoad(options: any) {
    const def = 'xhd_water'
    const value = wx.getStorageSync('filterDevName') || def
    
    // 检查是否从设备页面跳转过来
    const fromDevice = options?.fromDevice === 'true'
    
    console.log('配网页面加载参数:', {
      options: options,
      fromDevice: fromDevice
    });
    
    this.setData({ 
      filterDevName: value,
      fromDevice: fromDevice
    })
    
    try { wx.setStorageSync('filterDevName', value) } catch (e) {}
    this._filterDevName(this._foundSrcDevlist)
    {
      DeviceManager.observe(this._onRCSPBluetoothEvent)
    }
    {
      this._RCSPWrapperEventCallback = new RCSP.RCSPWrapperEventCallback()
      this._RCSPWrapperEventCallback.onEvent = (event) => {
        if (event.type === "onSwitchUseDevice") {
          const connectedDeviceId = event.onSwitchUseDeviceEvent?.device?.deviceId
          console.log(" onSwitchUseDevice111: " + connectedDeviceId);
          this.setData({
            connectedDeviceId: connectedDeviceId == undefined ? "" : connectedDeviceId
          })
          if (connectedDeviceId != undefined) {
            // 获取连接的设备信息
            const device = this.getConnectedDevice()
            
            console.log('设备连接成功，检查绑定条件:', {
              fromDevice: this.data.fromDevice,
              device: device,
              deviceId: device?.deviceId
            });
            
            // 如果是从设备页面跳转过来，则进行设备绑定
            if (this.data.fromDevice && device) {
              console.log('开始执行设备绑定流程...');
              this.bindDeviceToUser(device)
            } else {
              console.log('跳转到功能测试页面，原因:', {
                fromDevice: this.data.fromDevice,
                hasDevice: !!device
              });
              // 否则跳转到功能测试页面
              setTimeout(() => {
                wx.redirectTo({
                  url: '/pages/function_test/index'
                })
              }, 300);
            }
          }
        }
      }
      RCSPManager.observe(this._RCSPWrapperEventCallback)
      const curId = RCSPManager.getCurrentRcspOperateWrapper()?.deviceId || ''
      this.setData({ connectedDeviceId: curId })
    }

    // 初始化文案
    this.updateTexts()

    setTimeout(() => {
      if (wxBluetooth.bluetoothManager.isBluetoothAdapterAvailable() == false) {
        wxBluetooth.bluetoothManager.openBluetoothAdapter({
          success: () => {
            setTimeout(() => {
              DeviceManager.starScan()
            }, 200)
          },
          fail: () => {
            wx.showToast({ title: i18n.t('addDevice.bluetoothOff'), icon: "none" })
          }
        })
      } else {
        DeviceManager.starScan()
      }
    }, 500);
  },
  onShow() {
    this.updateTexts()
  },
  onUnload() {
    DeviceManager.removeObserve(this._onRCSPBluetoothEvent)
    RCSPManager.removeObserve(this._RCSPWrapperEventCallback)
  },
  isAdapter: false,
  onRefresh() {
    if (wxBluetooth.bluetoothManager.isBluetoothAdapterAvailable() == false) {
      this.setData({
        triggered: false,
      })
      console.log("打开蓝牙适配器");
      wxBluetooth.bluetoothManager.openBluetoothAdapter({
        success: () => {
          setTimeout(() => {
            this.onRefresh()
          }, 100);
        }, fail: () => {
          wx.showToast({ title: i18n.t('addDevice.bluetoothError') })
        }
      })
      return
    }

    console.log("onRefresh");
    if (this._freshing) return
    console.log("onRefresh111");
    this._freshing = true
    setTimeout(() => {
      this.setData({
        triggered: false,
      })
      this._freshing = false
    }, 500)
    if (DeviceManager.isScanning()) {
      DeviceManager.refreshScan()
      this.setData({
        triggered: false,
      })
      this.discoveryDevList = new Array()
      this.setData({ scanDevices: new Array() })
      this.setData({ isScaning: true })
      console.log("onRefresh222");
      return
    }
    DeviceManager.starScan()
  },
  // 下拉刷新空实现，避免控制台警告
  onPulling() {},
  onRestore() {},
  onSetFilter() {
    wx.showModal({
      title: i18n.t('addDevice.filterTitle'),
      editable: true,
      content: this.data.filterDevName,
      success: (res) => {
        if (res.confirm) {
          this.setData({
            filterDevName: res.content
          })
          this._filterDevName(this._foundSrcDevlist)
          wx.setStorageSync('filterDevName', res.content)
        } else if (res.cancel) {

        }
      }
    })
  },
  onConnectDev(e: any) {
    console.log("e : ", e);
    const dev = e.currentTarget.dataset.dev
    console.log("🔍 完整设备对象:", JSON.stringify(dev, null, 2));
    console.log("🔍 设备device属性:", JSON.stringify(dev.device, null, 2));
    console.log("🔍 设备deviceId:", dev.deviceId);
    const device = dev.device as BluetoothDevice
    const rcspOperateWrapper = RCSPManager.getCurrentRcspOperateWrapper()
    if (rcspOperateWrapper == undefined) {//有已连接设备
      DeviceManager.connecDevice(device)
    } else {
      if (rcspOperateWrapper.deviceId == dev.device.deviceId) {
        wx.showActionSheet({
          itemList: [i18n.t('addDevice.actionDisconnect'), i18n.t('addDevice.actionControl')],
          success: (res) => {
            if (res.tapIndex == 0) {//断开设备
              DeviceManager.disconnectDevice(device)
            } else if (res.tapIndex == 1) {//控制设备
              wx.redirectTo({
                url: '/pages/function_test/index'
              })
            }
          }
        })
      } else {
        wx.showToast({ title: i18n.t('addDevice.pleaseDisconnectFirst') })
      }
    }
  },
  cacheScanDevice: new Map(),
  discoveryDevList: Array(),//发现设备
  _onRCSPBluetoothEvent(event: DeviceBluetooth.DeviceBluetoothEvent) {
    if (event.type === 'onDiscoveryStatus') {
      if (event.onDiscoveryStatusEvent) {
        const bStart = event.onDiscoveryStatusEvent.bStart
        if (bStart) {//开始扫描
          this.discoveryDevList = new Array()
          this.setData({ scanDevices: new Array() })
          this.setData({ isScaning: true })
          wx.showToast({
            title: i18n.t('addDevice.scanStart'),
            icon: "none"
          })
        } else {//扫描结束
          this.setData({ isScaning: false })
          wx.showToast({
            title: i18n.t('addDevice.scanEnd'),
            icon: "none"
          })
        }
      }
    } else if (event.type === 'onDiscovery') {
      if (event.onDiscoveryEvent) {
        const device = event.onDiscoveryEvent.device
        const bleScanMassage = event.onDiscoveryEvent.bleScanMessage
        if (device.name === "") {
          return
        }
        let isContain = false
        for (let index = 0; index < this.discoveryDevList.length; index++) {
          const element = this.discoveryDevList[index];
          if (element.deviceId === device.deviceId) {
            isContain = true
            break;
          }
        }
        if (!isContain) {
          this.discoveryDevList.push({
            deviceId: device.deviceId,
            device: device,
            bleScanMassage: bleScanMassage
          })
          this._onFoundDevice(this.discoveryDevList)
        }
      }
    }
  },
  _onFoundDevice(devs: any[]) {
    const tempList = new Array()
    devs.forEach(element => {
      const devName = element.device.name
      const time = (new Date()).getTime()
      if (devName && devName !== '') {
        let cacheObj = this.cacheScanDevice.get(element.deviceId)
        if (cacheObj != undefined) {
          if (time - cacheObj.time > 2000) {//2s更新
            cacheObj.element = element
            cacheObj.time = time
            this.cacheScanDevice.set(element.deviceId, cacheObj)
          }
          tempList.push(cacheObj.element)
        } else {
          cacheObj = {}
          cacheObj.element = element
          cacheObj.time = time
          this.cacheScanDevice.set(element.deviceId, cacheObj)
          tempList.push(cacheObj.element)
        }
      }
    });
    tempList.sort(function (a, b) { return b.device.RSSI - a.device.RSSI })
    this._foundSrcDevlist = tempList
    this._filterDevName(this._foundSrcDevlist)
  },
  _filterDevName(devs: any[]) {
    const filterDevName = this.data.filterDevName.toLowerCase()
    const tempList = new Array()
    devs.forEach(e => {
      const devName = e.device.name?.toLowerCase()
      // 仅显示包含 JL707 的设备（由 filterDevName 控制）
      if (devName && devName.includes(filterDevName)) {
        tempList.push(e)
      }
    })
    this.setData({ scanDevices: tempList })
  },

  // 获取当前连接的设备信息
  getConnectedDevice() {
    try {
      const wrapper = RCSPManager.getCurrentRcspOperateWrapper()
      if (wrapper && wrapper.wrapper) {
        // 尝试从wrapper中获取设备信息
        const rcspOpImpl = wrapper.wrapper.getRcspOpImpl()
        if (rcspOpImpl) {
          const device = rcspOpImpl.getUsingDevice()
          if (device) {
            return device
          }
        }
      }
      
      // 如果通过wrapper获取不到，尝试从扫描列表中查找
      const connectedDeviceId = this.data.connectedDeviceId
      if (connectedDeviceId && this._foundSrcDevlist) {
        const foundDevice = this._foundSrcDevlist.find(item => 
          item.device.deviceId === connectedDeviceId
        )
        return foundDevice?.device
      }
      
      return null
    } catch (error) {
      console.error('获取连接设备信息失败:', error)
      return null
    }
  },

  // 多语言：构建/刷新文案
  updateTexts() {
    const l10n = {
      pullToRefresh: i18n.t('addDevice.pullToRefresh'),
      searching: i18n.t('addDevice.searching'),
      searchingTips: i18n.t('addDevice.searchingTips'),
      bindingAutoReturnTip: i18n.t('addDevice.bindingAutoReturnTip'),
      deviceName: i18n.t('device.deviceName'),
      btnConnected: i18n.t('addDevice.btnConnected'),
      btnTapToConnect: i18n.t('addDevice.btnTapToConnect')
    }
    try { wx.setNavigationBarTitle({ title: i18n.t('addDevice.title') }) } catch (e) {}
    this.setData({ l10n })
  },

  // 绑定设备到用户
  async bindDeviceToUser(device: any) {
    if (!device) {
      console.error('设备信息为空，无法绑定')
      return
    }

    try {
      this.setData({
        isBinding: true,
        bindingProgress: i18n.t('addDevice.progressFetching')
      })

      console.log('开始绑定设备到用户:', device.name)
      console.log('🔍 绑定设备对象详情:', JSON.stringify(device, null, 2));

      // 获取用户信息
      const app = getApp() as any
      let userInfo: any = null
      let userId: number | null = null

      try {
        // 尝试从app获取用户信息
        if (app.globalData && app.globalData.userInfo) {
          userInfo = app.globalData.userInfo
          userId = userInfo?.data?.id || userInfo?.id || userInfo?.userId
        }

        // 如果没有获取到，尝试调用API获取
        if (!userId) {
          const response = await api.getUserInfo()
          userInfo = response?.data?.data || response?.data
          userId = userInfo?.id || userInfo?.userId
        }

        // 如果还是没有，从本地存储获取
        if (!userId) {
          const localUserInfo = wx.getStorageSync('userInfo')
          userId = localUserInfo?.data?.id || localUserInfo?.id || localUserInfo?.userId
        }

        if (!userId) {
          throw new Error('无法获取用户信息，请先登录')
        }

        console.log('获取到用户ID:', userId)

      } catch (error) {
        console.error('获取用户信息失败:', error)
        throw new Error('获取用户信息失败，请重新登录')
      }

      this.setData({
        bindingProgress: i18n.t('addDevice.progressBinding')
      })

      // 尝试获取设备详细信息来获取真实MAC地址
      let realMacAddress = device.deviceId // 默认使用deviceId
      
      const rcspOperateWrapper = RCSPManager.getCurrentRcspOperateWrapper()
      if (rcspOperateWrapper && rcspOperateWrapper.deviceId === device.deviceId) {
        console.log('正在获取设备详细信息以获取真实MAC地址...')
        
        try {
          // 等待一下让设备完全连接
          await new Promise(resolve => setTimeout(resolve, 1000))
          
          const detailedInfo = RCSPManager.getDeviceInfo(device)
          console.log('📋 获取到的设备详细信息:', JSON.stringify(detailedInfo, null, 2))
          
          if (detailedInfo) {
            // 优先使用BLE地址，然后是EDR地址
            if (detailedInfo.bleAddr && detailedInfo.bleAddr !== '00:00:00:00:00:00') {
              realMacAddress = detailedInfo.bleAddr
              console.log('🔍 使用BLE地址作为MAC:', realMacAddress)
            } else if (detailedInfo.edrAddr && detailedInfo.edrAddr !== '00:00:00:00:00:00') {
              realMacAddress = detailedInfo.edrAddr
              console.log('🔍 使用EDR地址作为MAC:', realMacAddress)
            } else {
              console.log('⚠️ 未找到真实MAC地址，使用deviceId')
            }
          }
        } catch (error) {
          console.error('获取设备详细信息失败:', error)
        }
      }

      // 构造设备绑定数据
      const deviceInfo = {
        userId: parseInt(String(userId)),
        deviceSn: String(device.deviceId || `SWB_${Date.now()}`),
        deviceId: String(device.deviceId), // 蓝牙设备UUID (数据库新字段)
        macAddress: String(realMacAddress), // 真实MAC地址 (17字符限制)
        deviceName: String(device.name || i18n.t('device.deviceName')),
        model: 'SWB-2024',
        batteryLevel: 100, // 默认电量
        currentVolume: 0, // 默认水量
        waterTemperature: 25, // 默认温度
        deviceTimezone: 'Asia/Shanghai',
        deviceToken: `token_${Date.now()}`,
        bleAddress: String(realMacAddress) // 使用真实的蓝牙地址
      }

      console.log('设备绑定数据:', deviceInfo)

      // 调用绑定API
      console.log('📤 即将发送的绑定请求:', deviceInfo);
      const bindResult = await api.bindDevice(deviceInfo)
      console.log('📥 绑定设备响应:', bindResult);
      
      // 检查绑定结果 - 修复判断逻辑
      let isSuccess = false;
      let errorMessage = '';
      
      if (bindResult) {
        console.log('🔍 响应状态码:', bindResult.statusCode);
        console.log('🔍 响应数据:', bindResult.data);
        console.log('🔍 完整响应:', bindResult);
        
        if (bindResult.statusCode === 200) {
          if (bindResult.data) {
            if (bindResult.data.code !== undefined) {
              if (bindResult.data.code === "200" || bindResult.data.code === 200) {
                isSuccess = true;
              } else {
                errorMessage = bindResult.data.message || bindResult.data.msg || `业务错误: ${bindResult.data.code}`;
              }
            } else if (typeof bindResult.data === 'boolean') {
              if (bindResult.data === true) {
                isSuccess = true;
              } else {
                errorMessage = i18n.t('addDevice.bindFailedTry');
              }
            } else if (typeof bindResult.data === 'string') {
              if (bindResult.data.toLowerCase().includes('success') || bindResult.data.toLowerCase().includes('true')) {
                isSuccess = true;
              } else {
                errorMessage = bindResult.data;
              }
            } else if (bindResult.data.success !== undefined) {
              if (bindResult.data.success === true) {
                isSuccess = true;
              } else {
                errorMessage = bindResult.data.message || bindResult.data.msg || i18n.t('addDevice.bindFailedTry');
              }
            } else {
              const responseStr = JSON.stringify(bindResult.data).toLowerCase();
              if (responseStr.includes('error') || responseStr.includes('fail') || responseStr.includes('false')) {
                errorMessage = i18n.t('addDevice.bindFailedTry');
              } else {
                isSuccess = true;
              }
            }
          } else {
            if (bindResult.data === true || bindResult.data === "true") {
              isSuccess = true;
            } else {
              errorMessage = i18n.t('addDevice.responseError');
            }
          }
        } else {
          errorMessage = `HTTP错误: ${bindResult.statusCode}`;
        }
      } else {
        errorMessage = i18n.t('addDevice.noResponse');
      }
      
      if (!isSuccess) {
        console.error('🚨 绑定失败详情:', {
          statusCode: bindResult?.statusCode,
          data: bindResult?.data,
          response: bindResult,
          errorMessage: errorMessage,
          isSuccess: isSuccess
        });
        throw new Error(errorMessage || i18n.t('addDevice.bindFailedTry'));
      }

      // 绑定成功
      console.log('✅ 设备绑定成功!')
      console.log('📋 绑定成功详情:', {
        deviceInfo: deviceInfo,
        response: bindResult,
        timestamp: new Date().toISOString()
      });
      
      this.setData({
        bindingProgress: i18n.t('addDevice.bindSuccessReturning')
      })

      wx.showToast({
        title: i18n.t('addDevice.bindSuccess'),
        icon: 'success',
        duration: 2000
      })

      setTimeout(() => {
        this.returnToDevicePage()
      }, 2000)

    } catch (error) {
      console.error('设备绑定失败:', error)
      
      this.setData({
        isBinding: false,
        bindingProgress: ''
      })

      // 根据错误类型显示不同的提示信息
      let errorContent = i18n.t('addDevice.bindFailedTry');
      
      if (error instanceof Error) {
        const errorMsg = error.message.toLowerCase();
        if (errorMsg.includes('mac') || errorMsg.includes('地址')) {
          errorContent = i18n.t('addDevice.bindFailedBoundOther');
        } else if (errorMsg.includes('已被') || errorMsg.includes('冲突')) {
          errorContent = i18n.t('addDevice.bindFailedBound');
        } else {
          errorContent = error.message;
        }
      }

      wx.showModal({
        title: i18n.t('addDevice.bindFailedTitle'),
        content: errorContent,
        showCancel: true,
        confirmText: i18n.t('device.retry'),
        cancelText: i18n.t('common.cancel'),
        success: (res) => {
          if (res.confirm) {
            this.bindDeviceToUser(device)
          } else {
            this.returnToDevicePage()
          }
        }
      })
    }
  },

  // 返回设备页面
  returnToDevicePage() {
    console.log('返回设备页面...')
    
    if (this.data.fromDevice) {
      wx.navigateBack({
        delta: 1,
        success: () => {
          console.log('成功返回设备页面')
          const pages = getCurrentPages()
          const prevPage = pages[pages.length - 2] as any
          if (prevPage && prevPage.route === 'pages/device/device') {
            prevPage.setData({
              fromPairing: true
            })
            prevPage.onShow && prevPage.onShow()
          }
        },
        fail: (error) => {
          console.error('返回设备页面失败:', error)
          wx.redirectTo({
            url: '/pages/device/device?fromPairing=true'
          })
        }
      })
    } else {
      wx.redirectTo({
        url: '/pages/device/device?fromPairing=true'
      })
    }
  }
})
